<template>
  <div ref="vtkContainer" class="vtk-container"></div>
</template>

<script setup>
import { ref, onMounted, watch, onBeforeUnmount } from 'vue';
import axios from 'axios';
import { vtkRenderer, vtkRenderWindow, vtkRenderWindowInteractor } from '@kitware/vtk.js/Rendering/Core';
import vtkPolyDataReader from '@kitware/vtk.js/IO/Legacy/PolyDataReader'; // 正确的导入路径

const props = defineProps({
  filename: {
    type: String,
    default: '',
  },
});

const vtkContainer = ref(null);
let renderer = null;
let renderWindow = null;
let interactor = null;
let currentActor = null;

onMounted(() => {
  initializeVtk();
});

onBeforeUnmount(() => {
  if (renderWindow) {
    renderWindow.delete();
  }
});

watch(
  () => props.filename,
  (newFilename) => {
    if (newFilename) {
      loadVtkFile(newFilename);
    }
  },
  { immediate: true } // 立即执行一次，加载初始文件
);

const initializeVtk = () => {
  // 创建渲染器
  renderer = vtkRenderer.newInstance();
  renderer.setBackground(0.2, 0.3, 0.4); // 设置背景颜色

  // 创建渲染窗口
  renderWindow = vtkRenderWindow.newInstance();
  renderWindow.addRenderer(renderer);

  // 创建交互器
  interactor = vtkRenderWindowInteractor.newInstance();
  interactor.setRenderWindow(renderWindow);
  interactor.initialize();
  interactor.start();

  // 将渲染窗口附加到 DOM 容器
  if (vtkContainer.value) {
    const containerDiv = document.createElement('div');
    containerDiv.style.width = '100%';
    containerDiv.style.height = '100%';
    vtkContainer.value.appendChild(containerDiv);
    renderWindow.setView(containerDiv);
  }

  // 设置窗口大小调整处理
  window.addEventListener('resize', () => {
    if (renderWindow) {
      const container = vtkContainer.value;
      if (container) {
        renderWindow.setSize(container.clientWidth, container.clientHeight);
      }
    }
  });
};

const loadVtkFile = async (filename) => {
  if (!filename || !renderer) return;

  // 清理旧的actor
  if (currentActor) {
    renderer.removeActor(currentActor);
    currentActor.delete();
  }

  try {
    // 从后端获取VTK文件
    const response = await axios.get(
      `http://localhost:5000/api/vtk-file/content/${filename}`,
      { responseType: 'arraybuffer' }
    );

    // 创建reader
    const reader = vtkPolyDataReader.newInstance();
    reader.parseAsArrayBuffer(response.data);

    // 创建渲染管线
    const mapper = reader.getOutputData(0).getMapper();
    currentActor = vtkRenderer.vtkActor.newInstance();
    currentActor.setMapper(mapper);

    // 添加到渲染器
    renderer.addActor(currentActor);
    renderer.resetCamera();
    renderWindow.render();
  } catch (error) {
    console.error('加载VTK文件失败:', error);
  }
};
</script>

<style scoped>
.vtk-container {
  flex-grow: 1;
  height: 100vh;
  width: 100%;
}
</style>